package com.lysh.test.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liyishan
 * @date 2023/8/24 13:38
 * @apiNote   不好使
 */
@Slf4j
public class MyServerHandler4 extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        System.out.println("channelActive");
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("读取客户端的内容："+textWebSocketFrame.text());
        String text=textWebSocketFrame.text();
        if (text.equals("heard")){//处理心跳
            //响应heard到客户端
            TextWebSocketFrame heard = new TextWebSocketFrame("heard");
            channelHandlerContext.writeAndFlush(heard);
            return;
        }
        TextWebSocketFrame textWebSocketFrame1 = new TextWebSocketFrame("嗯");
        channelHandlerContext.writeAndFlush(textWebSocketFrame1);
    }



    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }
}
